package juc.day02;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/*
1.创建执行线程的方式3：实现Callable接口.相较于实现Runnable的接口方式，方法可以有返回值，并可以抛异常
2.执行Callable方式，需要FutureTask实现类来支持，用于接收运算结果。FutureTask是Future接口的实现类
 */
public class TestCallable {

    public static void main(String[] args) {
        ThreadDemo t = new ThreadDemo();

        //1.执行Called方式，需要FutureTask实现类的支持，用于接收运算结果
        FutureTask<Integer> f = new FutureTask<Integer>(t);

        new Thread(f).start();


        //2.接受线程运算后的结果

        try {
            System.out.println(f.get());//FutureTask可用于闭锁的操作
            System.out.println("-----------------------------------------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

class ThreadDemo implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i < 100; i++) {
            System.out.println(i);
            sum += i;
        }
        return sum;
    }
}
//class ThreadDemo implements Runnable{
//
//    @Override
//    public void run() {
//
//    }
//}